package cn.yunchongbao.charging.order.mqtt;

import cn.yunchongbao.charging.common.pojo.utils.JsonUtils;
import cn.yunchongbao.charging.order.constant.Constant;
import cn.yunchongbao.charging.order.constant.MqttConstant;
import cn.yunchongbao.charging.order.pojo.dto.ChargingResultDto;
import cn.yunchongbao.charging.order.pojo.po.ChargingBillFailPo;
import cn.yunchongbao.charging.order.pojo.po.ChargingBillSuccessPo;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class MqttConsumer implements MqttCallbackExtended {
    private MqttClient mqttClient;
    private MqttContext mqttContext;

    public MqttConsumer(MqttContext mqttContext, MqttClient mqttClient) {
        this.mqttContext = mqttContext;
        this.mqttClient = mqttClient;
    }

    @Override
    public void connectComplete(boolean b, String s) {
        log.debug("connectComplete被执行");
        try {
            log.debug("连接成功，订阅topic：{}",MqttConstant.TOPIC_CHARGING_RESULT);
            mqttClient.subscribe(MqttConstant.TOPIC_CHARGING_RESULT);
            log.debug("连接成功，订阅topic：{}成功",MqttConstant.TOPIC_CHARGING_RESULT);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void connectionLost(Throwable throwable) {
        log.debug("connectionLost被执行");
    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        log.debug("messageArrived被执行topic:{},message:{}",s,mqttMessage);
        ChargingResultDto chargingResultDto = null;
        try {
            chargingResultDto = JsonUtils.fromJson(mqttMessage.toString(), ChargingResultDto.class);
            log.debug("消息转换为Java对象：{}", chargingResultDto);
        } catch (Exception e) {
            log.error("消息转换为Java对象失败，格式有误：{}",mqttMessage);
        }
        if(chargingResultDto != null){
            String result = chargingResultDto.getResult();
            if(result.startsWith("0xFF")){
                // 去掉前缀 "0xFF"
                String substring = result.substring(4);
                // 截取接下来的两位字符
                String r = substring.substring(0, 2);
                System.out.println("截取的结果是: " + r);
                if(r.equals(Constant.START_CHARGING_RESULT_SUCCESS)){
                    log.debug("设备开始充电响应成功，保存订单信息成功：{}",chargingResultDto.getOrderNo());
                    ChargingBillSuccessPo chargingBillSuccessPo = new ChargingBillSuccessPo();
                    chargingBillSuccessPo.setBillId(chargingResultDto.getOrderNo());
                    mqttContext.getOrderSuccessMapper().insert(chargingBillSuccessPo);
                } else {
                    log.debug("设备开始充电失败");
                    ChargingBillFailPo chargingBillFailPo = new ChargingBillFailPo();
                    chargingBillFailPo.setBillId(chargingResultDto.getOrderNo());
                    chargingBillFailPo.setFailDesc("设备开始充电失败");
                    mqttContext.getOrderFailMapper().insert(chargingBillFailPo);
                }
            }
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.debug("deliveryComplete被执行");
    }
}
